<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="register-container">
      <!-- 左侧表单 -->
      <el-form class="input-section" label-width="80px" label-position="top">
        <el-form-item label="从机 ID:">
          <el-input v-model="slaveId" class="left-form-item" controls-position="right" />
        </el-form-item>

        <el-form-item label="起始地址:">
          <el-input
            v-model.number="address"
            class="left-form-item"
            controls-position="right"
          />
        </el-form-item>

        <el-form-item label="数量:">
          <el-input v-model="quantity" class="left-form-item" controls-position="right" />
        </el-form-item>

        <el-form-item label="线圈寄存器:">
          <div class="coil-register">
            <el-scrollbar>
              <el-checkbox-group v-model="checkedRegisters">
                <div
                  v-for="(row, rowIndex) in chunkedRegisterList"
                  :key="rowIndex"
                  class="checkbox-group"
                >
                  <el-checkbox
                    v-for="(register, index) in row"
                    :key="register.address"
                    :label="register.address"
                    style="margin-right: 10px; flex: 1"
                  />
                </div>
              </el-checkbox-group>
            </el-scrollbar>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <div class="button-group">
      <el-button @click="resetAll(1)">全部置1</el-button>
      <el-button type="primary" @click="writeRegister(WriteMethod.Single)"
        >(05)循环写入寄存器
      </el-button>
      <el-button
        type="primary"
        class="write-btn"
        @click="writeRegister(WriteMethod.Multiple)"
      >
        (15)连续写入寄存器
      </el-button>
    </div>
  </el-dialog>
</template>

<script setup name="coilRegister">
import { ref, watch, computed } from "vue";
import {
  getRegisterCount,
  InnerDecode,
  InnerDecodeList,
  ModbusFunctionCode,
  RegisterType,
  WriteMethod,
} from "@/types/register.ts";
import { writeRegister as writeRegisterApi } from "@/api/slaveApi.ts";
import { ElMessage } from "element-plus";

const props = defineProps({
  deviceName: {
    type: String,
    required: true,
  },
  slaveId: {
    type: Number,
    required: true,
  },
});

const dialogVisible = ref(false);
const title = ref("05/15：写线圈寄存器");
const slaveId = ref(1);
const address = ref(0);
const quantity = ref(10);
const registerList = ref([]);
// 初始化勾选状态
registerList.value.forEach((item) => {
  checkedRegisters.value[item.address] = 0;
});
const dataType = ref(InnerDecode.SignedShort);

// 假设 registerList 是响应式数据（如 ref 或 reactive）
const chunkedRegisterList = computed(() => {
  const chunkSize = 5;
  return registerList.value.reduce((result, item, index) => {
    const chunkIndex = Math.floor(index / chunkSize);
    (result[chunkIndex] ??= []).push(item);
    return result;
  }, []);
});
const checkedRegisters = ref([]);

watch(
  [() => quantity.value, () => address.value, () => dataType.value],
  () => {
    const registerSize = getRegisterCount(dataType.value);
    const actualQuantity = Math.ceil(quantity.value / registerSize);

    // 改为字典数组结构，每个元素包含address和value
    registerList.value = Array.from({ length: actualQuantity }, (_, i) => ({
      address: address.value + i * registerSize, // 寄存器地址
      value: false, // 初始值设为false
    }));
  },
  { immediate: true }
);

const resetAll = (value) => {
  checkedRegisters.value = registerList.value.map((item) => item.address);
};

const writeRegister = async (writeMethod) => {
  const values = registerList.value.map((item) => {
    return checkedRegisters.value.some((register) => register === item.address) ? 1 : 0;
  });
  let isSuccess = false;
  if (writeMethod === WriteMethod.Single) {
    isSuccess = await writeRegisterApi(
      props.deviceName,
      slaveId.value,
      RegisterType.coil,
      address.value,
      dataType.value,
      values,
      ModbusFunctionCode.WRITE_COIL_REGISTERS
    );
  } else {
    isSuccess = await writeRegisterApi(
      props.deviceName,
      slaveId.value,
      RegisterType.coil,
      address.value,
      dataType.value,
      values,
      ModbusFunctionCode.WRITE_MULTIPLE_COILS
    );
  }

  if (isSuccess) {
    ElMessage({
      type: "success",
      message: `写入寄存器成功!`,
      duration: 3000,
    });
  }
};

const openDialog = () => {
  dialogVisible.value = true;
};

const closeDialog = () => {
  dialogVisible.value = false;
};

// 如果需要从父组件控制对话框显示
defineExpose({
  openDialog,
  closeDialog,
});
</script>

<style scoped>
.register-container {
  gap: 30px;
  margin: 10px 10px 10px 10px;
}

.left-form-item {
  width: 200px;
}

.input-section {
  flex: 1;
  min-width: 200px;
}

.value-section .el-form-item {
  margin-bottom: 10px;
}

.checkbox-group {
  grid-template-columns: repeat(5, 1fr); /* 强制每行5列 */
  display: grid;
  justify-items: start; /* 防止内容拉伸填充 */
}

.button-group {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  gap: 10px;
}

::v-deep(.el-checkbox__inner) {
  width: 25px;
  height: 25px;
  border-width: 2px;
}

::v-deep(.el-checkbox__inner::after) {
  /* 勾线尺寸（按比例放大1.5倍） */
  width: 7px; /* 原5px → 7px */
  height: 14px; /* 原10px → 14px */
  border-width: 2px;

  /* 动态居中计算 */
  left: calc(50% - 4px); /* (25px/2) - (7px/2) ≈ 9px - 2px偏移修正 */
  top: calc(50% - 8px); /* (25px/2) - (14px/2) ≈ 5.5px */
  transform: rotate(45deg) translateY(-1px); /* 微调角度对齐 */
}

.coil-register {
  display: grid;
  justify-items: start; /* 防止内容拉伸填充 */
  gap: 10px;
  height: 150px;
}

/* 使用深度选择器穿透scoped限制 */
:deep(.write-btn) {
  background-color: #ff6d33 !important;
  border-color: #ff6d33 !important;
  color: white !important;
}

/* 处理悬停状态 */
:deep(.write-btn:hover) {
  background-color: #ff8d66 !important;
  border-color: #ff8d66 !important;
}

/* 处理点击状态 */
:deep(.write-btn:active) {
  background-color: #e65c2b !important;
  border-color: #e65c2b !important;
}
</style>
